import { defineStore } from 'pinia'
import { UserState } from '../types'
import store from '../pinia'

import Avatar from '@/assets/img_avatar.gif'
import {UserInfo} from "@/views/model/model";
import {post, Response} from "@/api/http";
import {changeUseInfo, getLifeModeItemSelect, getUseInfo} from "@/api/url";

const defaultAvatar = Avatar

const useUserStore = defineStore('user-info', {
  state: () => {
    return {
      userId: 0,
      roleId: 0,
      token: '',
      sessionId:'',
      userName: '',
      nickName: '',
      avatar: defaultAvatar,
      timezone:''
    }
  },
  actions: {
    getUserInfo:async function(){
      try {
        const data: Response = await post({
          url: getUseInfo,
          token:this.getToken()
        });
        data.data.data.avatar = this.avatar
        this.timezone = data.data.data.timezone;
        return data.data.data as UserInfo
      }catch(e) {

      }finally {
      }
      return UserInfo.getNewUserInfo();
    },
    saveUserInfo:async function(userInfo: UserInfo|null){
      if(userInfo)
      try {
        const data: Response = await post({
          url: changeUseInfo,
          data:userInfo,
          token:this.getToken()
        });
        this.userName = userInfo.name
        this.nickName = userInfo.name
        this.timezone = userInfo.timezone;
        return data.msg;
      }catch(e) {
        return (e as Error).message;
      }finally {
      }
    },
    getToken():object{
      return {token:this.token,userName:this.token,sessionId:this.sessionId};
    },
    setSessionId(sessionId:string){
      this.sessionId = sessionId
    },
    saveUser(userInfo: UserState) {
      return new Promise<UserState>((resolve) => {
        this.userId = userInfo.userId
        this.roleId = userInfo.roleId
        this.token = userInfo.token
        this.sessionId = userInfo.sessionId
        this.userName = userInfo.userName
        this.nickName = userInfo.nickName
        this.avatar = userInfo.avatar || defaultAvatar
        resolve(userInfo)
      })
    },
    isTokenExpire() {
      return !this.token
    },
    changeNickName(newNickName: string) {
      this.nickName = newNickName
    },
    logout() {
      return new Promise<void>((resolve) => {
        this.$reset()
        localStorage.clear()
        sessionStorage.clear()
        resolve()
      })
    },
  },
  presist: {
    enable: true,
    resetToState: true,
    option: {
      exclude: ['userName'],
    },
  },
})

export default useUserStore

export function useUserStoreContext() {
  return useUserStore(store)
}
